package com.sxbbc.common.basics.push;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import org.apache.log4j.Logger;

/**
 * 消息推送 工具类
 *
 * @author leehao
 * @date 2019-06-17
 */
public class AppPushUtil {
    private static Logger log = Logger.getLogger(AppPushUtil.class);

    private static AppPushUtil appPushUtil = null;

    public static AppPushUtil getInstance() {
        if (appPushUtil == null) {
            synchronized (AppPushUtil.class) {
                if (appPushUtil == null) {
                    appPushUtil = new AppPushUtil();
                }
            }
        }
        return appPushUtil;
    }

    /**
     * 指定推送
     * @param key
     * @param secret
     * @param token
     * @param content
     * @return
     */
    public PushResult pushAndroidAndIos(String key, String secret, String token, String content) {
        PushResult result = null;
        try {
            JPushClient jpushClient = new JPushClient(secret, key, 86400);
            PushPayload payLoad = PushUtil.getInstance().buildPushObject(token, content);
            result = jpushClient.sendPush(payLoad);
        } catch (APIConnectionException e) {
            e.printStackTrace();
            log.info("Connection error, should retry later " + e);
        } catch (APIRequestException e) {
            log.info("HTTP Status: " + e.getStatus() + "Error Code: " + e.getErrorCode() + "Error Code: " + e.getErrorCode() + "Error Message: " + e.getErrorMessage());
        }
        return result;
    }


    /**
     * 推送全部客户
     * @param key
     * @param secret
     * @param content
     * @return
     */
    public PushResult pushAllAndroidAndIos(String key, String secret,String content) {
        PushResult result = null;
        try {
            JPushClient jpushClient = new JPushClient(secret, key, 86400);
            PushPayload payLoad = PushUtil.getInstance().buildAllPushObject(content);
            result = jpushClient.sendPush(payLoad);
        } catch (APIConnectionException e) {
            e.printStackTrace();
            log.info("Connection error, should retry later " + e);
        } catch (APIRequestException e) {
            log.info("HTTP Status: " + e.getStatus() + "Error Code: " + e.getErrorCode() + "Error Code: " + e.getErrorCode() + "Error Message: " + e.getErrorMessage());
        }
        return result;
    }
}
